package logic

import (
	"context"
	"io"
	"net/http"
	"strconv"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type AskListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAskListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AskListLogic {
	return &AskListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AskListLogic) AskList(req *types.AskListReq) (resp *types.AskListResp, err error) {
	// todo: add your logic here and delete this line
	url := "https://api.nutpi.net/queryQuestionList?page=" + req.Page + "&filterCondition=" + req.Filter + "&questionTagId=" + req.QId
	res, err_ := httpc.Do(l.ctx, http.MethodGet, url, nil)
	if err_ != nil {
		l.Error(err_)
		return nil, err_
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body:", err)
		return nil, err
	}
	//格式化输出json
	//var str bytes.Buffer
	//_ = json.Indent(&str, []byte(body), "", "    ")
	//l.Debugf("formated: ", str.String())
	//l.Debug(keyValue)
	var responseData []types.AskItem
	var item types.AskItem
	recs := gjson.GetBytes(body, "records")
	recs.ForEach(func(key, value gjson.Result) bool {
		item.Id = value.Get("id").String()
		item.Title = value.Get("title").String()

		item.Summary = value.Get("summary").String()
		item.Content = ""
		item.PostTime = value.Get("postTime").String()
		item.Avatar = value.Get("avatarPath").String() + value.Get("avatarName").String()
		item.ViewCnt = value.Get("viewTotal").String()
		item.AnswerTotal = value.Get("answerTotal").String()
		item.Nickname = value.Get("nickname").String()
		// 解析 questionTagAssociationList
		tagAssociations := value.Get("questionTagAssociationList")
		tagAssociations.ForEach(func(_, tagValue gjson.Result) bool {
			var tag types.QTag
			tag.Id = tagValue.Get("id").String()
			tag.Name = tagValue.Get("questionTagName").String()
			tag.TagId = tagValue.Get("questionTagId").String()
			tag.QId = tagValue.Get("questionId").String()
			item.Tags = append(item.Tags, tag)
			return true
		})

		//l.Info("id: %s, title: %s\n", item.Id, item.Title)
		responseData = append(responseData, item)
		return true // keep iterating
	})

	//t := reflect.TypeOf(keyVal["count"])
	//l.Debugf("Type: %v\n", t)
	start, err := strconv.ParseInt(req.Page, 10, 64)
	if err != nil {
		// 处理错误
		start = 0
	}
	total, err := strconv.ParseInt(gjson.GetBytes(body, "totalrecord").String(), 10, 64)
	if err != nil {
		// 处理错误
		total = 0
	}
	if len(responseData) != 0 {
		resp = &types.AskListResp{
			Code:    0,
			Message: res.Status,
			Data:    responseData,
			Count:   len(responseData),
			Start:   int(start),
			Total:   int(total),
		}
	} else {
		resp = &types.AskListResp{
			Code:    400,
			Message: res.Status,
			Data:    responseData,
			Count:   0,
			Start:   0,
			Total:   0,
		}
	}
	return resp, nil

}
